package test;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class Photos {
    /**
     * 图片转换为二进制流
     *
     * @param imgaddress 图片本地地址
     * @return 返回图片转换后的二进制流（类型：String）
     * @return 若转换失败返回 null
     */
    public static byte[] imgtoio(String imgaddress) {
        //图片转化为二进制
        byte[] imageBytes = null;
        try (FileInputStream fileInputStream = new FileInputStream(new File(imgaddress));) {
            imageBytes = new byte[fileInputStream.available()];
            fileInputStream.read(imageBytes);
        } catch (IOException e) {
            System.out.println(e);
            return null;
        }

        return imageBytes;
    }


    public static String UnicodeByteToStr(byte[] b) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < b.length; i++) {
            sb.append(String.format("%02x", b[i]));
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        byte[] imgtoio = imgtoio("C:\\Users\\xiongqiang\\Desktop\\乐炎\\企业微信截图_17222186205584.png");
        System.out.println(imgtoio.toString());

                try {
                    // 将二进制数据转换为字节数组输入流
                    ByteArrayInputStream inputStream = new ByteArrayInputStream(imgtoio);

                    // 使用ImageIO读取输入流并将其转换为BufferedImage对象
                    BufferedImage image = ImageIO.read(inputStream);

                    // 将BufferedImage对象保存为图片文件
                    File outputFile = new File("output.png");
                    ImageIO.write(image, "jpg", outputFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }

    }

}
